<?php
namespace app\ausagent\controller;

use think\Request;
use think\Db;
use think\Session;
use think\Cookie;
use think\Controller;
use think\Config;
use Godok\Org\Auth;
use think\Cache;
use think\Loader;
/**
 * Login Controller
 */
class Login extends Controller
{
	/**
	 * 首页
	 */
    // http://127.0.0.1/ausagent/Login/index
	public function index(){
	    if ( Request::instance()->isPost() ) {
	        // 做一个简单的登录 组合where数组条件
	        $username = Request::instance()->post('username', '', 'Godok\Org\Filter::username');
	        if( empty( $username ) ) {
	            return ['code'=>-1001,'msg'=>'用户名格式错误！'];
	        }
	        $password =Request::instance()->post('password', '', 'Godok\Org\Filter::password');
	        if( empty( $password ) ) {
	            return ['code'=>-1002,'msg'=>'密码格式错误！'];
	        }
	        $identifying = input('identifying');
	        $password = md123( $password );
	        $b = "operator";
	        Cookie::set('username', $username, 3600*24*7);
	        //$data=Db::name( Config::get('auth.table_user') )->where(['username' => $username,'deleted'=>0])->find();
	        $data = Db::name(Config::get('auth.table_user'))
	        		->alias('a')
	        		->join("$b b",'a.oid = b.id')
	        		->field('a.*,b.identifying')
	        		->where(['a.username' => $username,'a.deleted'=> 0,'b.identifying'=>$identifying])
	        		->find();
	        //ar_dump($data);die;
	        if (empty($data)) {
	            return ['code'=>-1000,'msg'=>'用户名错误'];
	        } elseif ($data['password'] != $password) {
	            return ['code'=>-1010,'msg'=>'密码错误'];
	        } elseif ( 0 == $data['status']) {
	            return ['code'=>-1020,'msg'=>'帐号被禁用'];
	        } elseif ( 2 == $data['status']) {
	            return ['code'=>-1030,'msg'=>'帐号审核中'];
	        } elseif ($data['identifying'] != $identifying){
	        	return ['code' =>-1040,'msg'=>'企业标识符不正确'];
	        }else {
	            $user=[
	                'id'=>$data['id'],
	                'oid' => $data['oid'],
	                'username'=>$data['username'],
	                'nickname'=>$data['nickname'],
	                'avatar'=>$data['avatar'],
	                'phone'=>$data['phone'],
	                'identifying' =>$data['identifying'],
	                'rules'=>[],
	                'groupids'=>[]
	            ];
	            //Cookie::set('avatar', $data['avatar'] ?: Config::get('site.resource_url').'images/avatar/default.jpg', 3600*24*7);
	            //Cookie::set('nickname', $data['nickname'], 3600*24*7);
	            if($data['avatar']){
	            	$avatar = Config::get('resourceurl').$data['avatar'];
	            	Session::set('avatar',$avatar);
	            }else{
	            	$avatar = Config::get('site.resource_url').'images/a1.png';
	            	Session::set('avatar',$avatar);
	            }
	            
	            Session::set('oid',$data['oid']);//oid 改为 直营商1/代理商大于1
	            Session::set('nickname',$data['username']);//用户昵称
	            Session::set('id',$data['id']);//用户ID
	            Session::set('identifying',$data['identifying']);

	            //获取权限组信息
	            
	            $groups = Auth::getGroups( $data['id'] );
	            $group23 = Db::name( Config::get('auth.table_group') )->field('id,rules')->where('id IN(2,3) AND status=1')->select();
	           $groups = array_merge($groups,$group23);
	            
	            if (empty($groups)) {

	                return ['code'=>-1040,'msg'=>'帐号无权限'];
	            } else {
	                $rules = '';
	                foreach ( $groups as $group) {
	                    $rules .= $rules ? ',' . $group['rules'] : $group['rules'];
	                    if ($group['id'] !=2 && $group['id'] != 3) {
	                        $user['groupids'][] = $group['id'];
	                    }
	                    
	                }

	                if ( !empty($rules) ) {

	                    $user['rules'] = array_unique( explode(',', $rules) );
	                }
	                //var_dump($user);die;
	                $user['_freshtime'] = time();
	            }
	            //判断用户组是否被禁用
	            Auth::clear();
	            //var_dump($user);die;
	            Auth::user($user);
	            //保存登录信息
	            Db::name( Config::get('auth.table_user') )
	            ->where(['id' => $data['id']])
	            ->update([
	            'last_login_ip' => Request::instance()->ip(),
	            'last_login_time' => time()
	            ]);
	            $oid = session('oid');$m = 'ausagent'; $c = 'Login'; $action="index"; $uid=session('id'); $querystring = '普通登录成功!';
		        $ip = get_ip();$os = get_os();
		        set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
	            return ['code'=>0,'msg'=>'登录成功','url'=>\think\Request::instance()->root().'/ausagent/Index/index'];
	        }
	    } else {
	    	$key = $this ->createkey();

	        return $this->fetch();
	    }
        
	}

	//创建用户二维码登陆的KEY
	public function createkey(){
		$key = rand(1000000000000,9999999999999).time(); //生成随机字符串
		$data = array(
			'time' => time(), 
			'broswer' => get_broswer(), 
			'ip' => get_ip(), 
			'os' => get_os(), 
		);
		$newkey = mwencrypt($key.'|'.$data['time']); //奖数据加密后生成key
		Cache::set($key,$data,120);  //将KEY写入缓存
		return $newkey;  
	}
	//生成二维码
	public function scancode(){
		ob_clean();//这个一定要加上，清除缓冲区  
    	$key = input('param.key');

    	$website = config('qrcodeurl');
    	$url = $website .'/operatorlogin?key='.$key;
    	
        $errorCorrectionLevel ='L';//容错级别
        $matrixPointSize = intval(18);//生成图片大小

        Loader::import('qrcode.phpqrcode');
        //生成二维码图片
        \QRcode::png($url, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = 'qrcode.png';//已经生成的原始二维码图 
        $QR = imagecreatefromstring(file_get_contents($QR)); //打开文件
        //输出图片 
        Header("Content-type: image/png");
        ImagePng($QR);

        die();
	}
	//验证扫码登陆
	public function validatescancode(){
		$newkey = input('param.key');
		if(!$newkey){
			die('非法请求！');
		}
		$newkey = mwdecrypt($newkey);  //解密key
		$newkey = explode("|",$newkey);  //转为字符串
		$key = $newkey[0];
		$time = $newkey[1];

		$data = Cache::get($key);

		if(!$data){
			$info['code'] = 1;
			$info['msg'] = '二维码已失效！';
			return $info;
		}
		
		if(isset($data['uid'])&&isset($data['oid'])){

			Cache::rm($key);//删除缓存 
		


			$b = "operator";
			$data = Db::name(Config::get('auth.table_user'))
	        		->alias('a')
	        		->join("$b b",'a.oid = b.id')
	        		->field('a.*,b.identifying')
	        		->where(['a.id' => $data['uid'],'a.deleted'=> 0])
	        		->find();
	        $user=[
	                'id'=>$data['id'],
	                'oid' => $data['oid'],
	                'username'=>$data['username'],
	                'nickname'=>$data['nickname'],
	                'avatar'=>$data['avatar'],
	                'phone'=>$data['phone'],
	                'identifying' =>$data['identifying'],
	                'rules'=>[],
	                'groupids'=>[]
	            ];
	            Session::set('oid',$data['oid']);//运营商ID
	            Session::set('nickname',$data['nickname']);//用户昵称
	            Session::set('id',$data['id']);//用户ID
	            Session::set('identifying',$data['identifying']);

	            //获取权限组信息
	            $groups = Auth::getGroups( $data['id'] );
	            $group23 = Db::name( Config::get('auth.table_group') )->field('id,rules')->where('id IN(2,3) AND status=1')->select();
	            $groups = array_merge($groups,$group23);
	            if (empty($groups)) {
	                return ['code'=>-1040,'msg'=>'帐号无权限'];
	            } else {
	                $rules = '';
	                foreach ( $groups as $group) {
	                    $rules .= $rules ? ',' . $group['rules'] : $group['rules'];
	                    if ($group['id'] !=2 && $group['id'] != 3) {
	                        $user['groupids'][] = $group['id'];
	                    }
	                    
	                }
	                if ( !empty($rules) ) {
	                    $user['rules'] = array_unique( explode(',', $rules) );
	                }
	                
	                $user['_freshtime'] = time();
	            }
	            //判断用户组是否被禁用
	            Auth::clear();
	            Auth::user($user);
	            //保存登录信息
	            Db::name( Config::get('auth.table_user') )
	            ->where(['id' => $data['id']])
	            ->update([
	            'last_login_ip' => Request::instance()->ip(),
	            'last_login_time' => time()
	            ]);
	            $oid = session('oid');$m = 'ausagent'; $c = 'Login'; $action="logout"; $uid=session('id'); $querystring = '扫码登录';
		        $ip = get_ip();$os = get_os();
		        set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
	            return ['code'=>0,'msg'=>'登录成功','url'=>\think\Request::instance()->root().'/ausagent/Index/index'];



		}elseif(isset($data['scancode'])){
			$info['code'] = 2;
			$info['msg'] = '扫码成功，等待手机点击登陆！';
			return $info;
		}else{
			$info['code'] = 3;
			$info['msg'] = '暂未登陆！';
			return $info;
		}

	}
    /**
     * 退出
     */
    // http://127.0.0.1/ausagent/Login/logout
    public function logout()
    {
    	if(session('id')){
    		$id = session('id');
    		$soid = session('oid');
    	}
    	
        Auth::clear();
       	session(null);
       	cookie(null);
       // $this->success('退出成功、前往登录页面',\think\Request::instance()->root().'/ausagent/Login/index');
       if(isset($soid)){
       		$oid = $soid;$m = 'ausagent'; $c = 'Login'; $action="logout"; $uid=$id; $querystring = '注销登录';
		    $ip = get_ip();$os = get_os();
		    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
       }
       
       $this->redirect('index');
    }

    /**
     * 忘记密码
     */
    public function forget()
    {
        return $this->fetch();
    }



}

